package org.codehaus.activemq.util;

import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

public abstract class MessageListenerSupport
  implements MessageListener
{
  private ExceptionListener exceptionListener;

  public void onMessage(Message message)
  {
    try
    {
      processMessage(message);
    }
    catch (JMSException e) {
      onJMSException(e, message);
    }
    catch (Exception e)
    {
      JMSException jmsEx = JMSExceptionHelper.newJMSException(e.getMessage(), e);
      onJMSException(jmsEx, message);
    }
  }

  public ExceptionListener getExceptionListener() {
    return this.exceptionListener;
  }

  public void setExceptionListener(ExceptionListener exceptionListener) {
    this.exceptionListener = exceptionListener;
  }

  protected abstract void processMessage(Message paramMessage)
    throws Exception;

  protected void onJMSException(JMSException e, Message message)
  {
    if (this.exceptionListener != null) {
      this.exceptionListener.onException(e);
    }
    else
      throw new RuntimeException("Failed to process message: " + message + " Reason: " + e, e);
  }
}